#!/bin/sh /etc/rc.common
#
# SPDX-License-Identifier: GPL-2.0-only
#
# shellcheck disable=SC3043 # ash supports local

PROG=/usr/bin/AdGuardHome

USE_PROCD=1

# matches dnsmasq
START=19
# stops before networking stops
STOP=89

config_cb() {
	[ $# -eq 0 ] && return

	option_cb() {
		local option="$1"
		local value="$2"

		case $option in

		# Support old option names
		config)
			option='config_file'
			;;

		workdir)
			option='work_dir'
			;;

		esac

		eval $option="$value"
	}
}

boot() {
	ADGUARDHOME_BOOT=1
	start "$@"
}

start_service() {
	if [ -n "$ADGUARDHOME_BOOT" ]; then
		# Do not start yet, wait for triggers
		return 0
	fi

	local config_file='/etc/adguardhome/adguardhome.yaml'
	local group='adguardhome'
	local user='adguardhome'
	local verbose=0
	local work_dir='/var/lib/adguardhome'

	config_load 'adguardhome'

	local config_dir
	config_dir=$(dirname "$config_file")
	if [ "$config_dir" = '/etc' ]; then
		echo "AdGuard Home config must be stored in its own directory, and not in /etc" >&2
		return 1
	fi
	mkdir -m 0700 -p "$config_dir"
	chown -R "$user":"$group" "$config_dir"

	mkdir -m 0700 -p "$work_dir"
	chown -R "$user":"$group" "$work_dir"

	procd_open_instance

	procd_set_param command "$PROG"
	procd_append_param command --config "$config_file"
	procd_append_param command --logfile syslog
	procd_append_param command --no-check-update
	[ "$verbose" = 1 ] && \
		procd_append_param command --verbose
	procd_append_param command --work-dir "$work_dir"

	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param user "$user"
	procd_set_param group "$group"
	procd_set_param capabilities /etc/capabilities/adguardhome.json
	procd_set_param no_new_privs 1

	# log is needed for logging to syslog instead of stdout
	# procfs is needed to readlink /proc/self/exe
	procd_add_jail adguardhome log procfs

	# config directory must be writable to write new config files
	procd_add_jail_mount_rw "$config_dir"
	procd_add_jail_mount_rw "$work_dir"

	procd_add_jail_mount /etc/hosts
	procd_add_jail_mount /etc/ssl/certs
	config_list_foreach config jail_mount procd_add_jail_mount

	procd_close_instance
}

service_triggers() {
	if [ -n "$ADGUARDHOME_BOOT" ]; then
		# Wait for interfaces to be up before starting AdGuard Home for real.
		# Prevents issues like https://github.com/openwrt/packages/issues/21868.
		procd_add_raw_trigger "interface.*.up" 5000 /etc/init.d/adguardhome restart
	fi
}
